package com.ftd.lampcontrol.server.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ftd.lampcontrol.server.dao.AppUserDao;
import com.ftd.lampcontrol.server.dto.AppUserDto;
import com.ftd.lampcontrol.server.model.AppUser;
import com.ftd.lampcontrol.server.model.Device;
import com.ftd.lampcontrol.server.model.Group;
import com.ftd.lampcontrol.server.model.Result;
import com.ftd.lampcontrol.server.service.AppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ftd.lampcontrol.server.annotation.LogAnnotation;
import com.ftd.lampcontrol.server.page.table.PageTableHandler;
import com.ftd.lampcontrol.server.page.table.PageTableHandler.CountHandler;
import com.ftd.lampcontrol.server.page.table.PageTableHandler.ListHandler;
import com.ftd.lampcontrol.server.page.table.PageTableRequest;
import com.ftd.lampcontrol.server.page.table.PageTableResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户相关接口
 *
 * @author tangxianfeng 656274354@qq.com
 */
@Api(tags = "用户")

@RestController
@RequestMapping("/appusers")
public class AppUserController {

    private static final Logger log = LoggerFactory.getLogger("adminLogger");

    @Autowired
    private AppUserService userService;
    @Autowired
    private AppUserDao appUserDao;

    @LogAnnotation
    @PostMapping("/add")
    @ApiOperation(value = "保存用户")
    public AppUser saveUser(@RequestBody AppUserDto userDto) {
        AppUser u = userService.getAppUser(userDto.getAccount());
        if (u != null) {
            throw new IllegalArgumentException(userDto.getUsername() + "已存在");
        }
        return userService.saveAppUser(userDto);
    }

    @LogAnnotation
    @PostMapping("/Appadd")
    @ApiOperation(value = "手机端保存用户")
    public Result<AppUser> AppsaveUser(@RequestBody AppUserDto userDto) {
        AppUser u = userService.getAppUser(userDto.getAccount());
        Result result=new Result();
        if (u != null) {
            result.setCode("209");
            result.setMsg("用户已存在");
        }else {
            result.setCode("200");
            result.setMsg("succese");
            result.setData(userService.saveAppUser(userDto));
        }
        return result;
    }

    @LogAnnotation
    @PutMapping("/Appupdate")
    @ApiOperation(value = "手机端修改用户")
    public Result<AppUser> AppupdateUser(@RequestBody AppUserDto userDto) {
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        result.setData(userService.updateAppUser(userDto));
        return result;
    }

    @LogAnnotation
    @PutMapping("/update")
    @ApiOperation(value = "修改用户")
    public AppUser updateUser(@RequestBody AppUserDto userDto) {
        return userService.updateAppUser(userDto);
    }

    @LogAnnotation
    @PutMapping(params = "headImgUrl")
    @ApiOperation(value = "修改头像")
    public void updateHeadImgUrl(String headImgUrl) {
        log.info(headImgUrl);
    }

    @LogAnnotation
    @PutMapping("/{username}")
    @ApiOperation(value = "修改密码")
    public void changePassword(@PathVariable String username, String oldPassword, String newPassword) {
        userService.changePassword(username, oldPassword, newPassword);
    }

    @GetMapping
    @ApiOperation(value = "用户列表")
    public PageTableResponse listUsers(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return appUserDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<AppUser> list(PageTableRequest request) {
                List<AppUser> list = appUserDao.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }


    @GetMapping("/grouplist")
    @ApiOperation(value = "设备组列表")
    public PageTableResponse listGroups(PageTableRequest request) {
        Long userid = Long.parseLong((String) request.getParams().get("userid"));
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return appUserDao.countGroup(request.getParams(), userid);
            }
        }, new ListHandler() {
            @Override
            public List<Group> list(PageTableRequest request) {
                List<Group> list = appUserDao.listGroup(userid, request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }

    @ApiOperation(value = "根据用户id获取用户")
    @GetMapping("/get/{id}")
    public AppUser user(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getById(id)));
        return appUserDao.getById(id);
    }

    @ApiOperation(value = "手机端根据用户id获取用户")
    @GetMapping("/Appget/{id}")
    public Result<AppUser> app_user(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getById(id)));
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        result.setData(appUserDao.getById(id));
        return result;
    }

    @ApiOperation(value = "手机端根据用户id获取设备组")
    @GetMapping("/grouplist/Appget/{id}")
    public Result<List<Group>> Appgroup(@PathVariable Long id) {
        log.info("Group" + id);
        log.info(id + "" + JSON.toJSON(appUserDao.getGroupById(id)));
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        List<Group> groups = appUserDao.getGroupById(id);
        List<Group> fgroup = new ArrayList<>();
        for (Group group : groups) {
            group.setDeviceSet(appUserDao.getDeviceById(group.getId()));
            if (group.getDeviceSet()!=null){
                group.setDevicenum(group.getDeviceSet().size());
            }else {
                group.setDevicenum(0);
            }
            fgroup.add(group);
            log.info("Group" + group.toString());
        }
        result.setData(fgroup);
        return result;
    }
    @ApiOperation(value = "根据用户id获取设备组")
    @GetMapping("/grouplist/get/{id}")
    public List<Group> group(@PathVariable Long id) {
        log.info("Group" + id);
        log.info(id + "" + JSON.toJSON(appUserDao.getGroupById(id)));
        List<Group> groups = appUserDao.getGroupById(id);
        List<Group> fgroup = new ArrayList<>();
        for (Group group : groups) {
            group.setDeviceSet(appUserDao.getDeviceById(group.getId()));
            if (group.getDeviceSet()!=null){
                group.setDevicenum(group.getDeviceSet().size());
            }else {
                group.setDevicenum(0);
            }
            fgroup.add(group);
            log.info("Group" + group.toString());
        }
        return fgroup;
    }
    @ApiOperation(value = "App用户登录")
    @GetMapping(value = "/loginApp")
    public Result<AppUser> loginUser(HttpServletRequest req) {
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        Result result=new Result();
        if (appUserDao.checkAccount(account) != null) {
            AppUser appUser=appUserDao.checkAccount(account);
            log.info("Group" + appUser.toString());
            if (appUser.getPassword().equals(password)){
                result.setCode("200");
                result.setMsg("succese");
                result.setData(appUser);
            }else {
                result.setCode("209");
                result.setMsg("密码错误");
            }
        }else {
            result.setCode("209");
            result.setMsg("用户不存在");
        }
        return result;
    }

    @ApiOperation(value = "根据组id获取当前设备组")
    @GetMapping("/grouplist/getone/{id}")
    public Group groupOne(@PathVariable Long id) {
        log.info("Group" + id);
        log.info(id + "" + JSON.toJSON(appUserDao.getGroupById(id)));
        return appUserDao.getOneGroupById(id);
    }


    @LogAnnotation
    @PostMapping("/grouplist/add")
    @ApiOperation(value = "保存设备组")
    public int saveGroup(@RequestBody Group group) {
        return userService.saveGroup(group);
    }
    @DeleteMapping("/grouplist/delete/{id}")
    @ApiOperation(value = "删除设备组")
    public void deleteGroup(@PathVariable Long id) {
        appUserDao.deleteGroup(id);
    }

    @LogAnnotation
    @PutMapping("/grouplist/update")
    @ApiOperation(value = "更新设备组")
    public void updateGroup(@RequestBody Group group) {
        Date date = new Date();
        appUserDao.upDateGroup(group.getId(), group.getGroupname(), group.getGroupbackname(), date);
    }
    @LogAnnotation
    @PostMapping("/grouplist/Appadd")
    @ApiOperation(value = "手机端保存设备组")
    public Result app_saveGroup(@RequestBody Group group) {
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        userService.saveGroup(group);
        return result;
    }

    @DeleteMapping("/grouplist/Appdelete/{id}")
    @ApiOperation(value = "手机端删除设备组")
    public Result app_deleteGroup(@PathVariable Long id) {
        appUserDao.deleteGroup(id);
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        return result;
    }

    @LogAnnotation
    @PutMapping("/grouplist/Appupdate")
    @ApiOperation(value = "手机端更新设备组")
    public Result app_updateGroup(@RequestBody Group group) {
        Date date = new Date();
        appUserDao.upDateGroup(group.getId(), group.getGroupname(), group.getGroupbackname(), date);
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        return result;
    }

    @ApiOperation(value = "手机端根据组id获取设备")
    @GetMapping("/devicelist/Appget/{id}")
    public List<Device> app_devices(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getDeviceById(id)));
        return appUserDao.getDeviceById(id);
    }

    @ApiOperation(value = "手机端根据设备id获取当前设备")
    @GetMapping("/devicelist/Appgetone/{id}")
    public Result<Device> app_deviceOne(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getDeviceById(id)));
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        result.setData(appUserDao.getOneDeviceById(id));
        return result;
    }
    @LogAnnotation
    @PostMapping("/devicelist/Appadd")
    @ApiOperation(value = "手机端保存/添加设备")
    public Result app_saveDevice(@RequestBody Device device) {
        appUserDao.saveDevice(device);
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        return result;

    }

    @DeleteMapping("/devicelist/Appdelete/{id}")
    @ApiOperation(value = "手机端删除设备")
    public Result app_deleteDevice(@PathVariable Long id) {
        appUserDao.deleteDevice(id);
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        return result;

    }

    @LogAnnotation
    @PutMapping("/devicelist/Appupdate")
    @ApiOperation(value = "手机端更新设备")
    public Result app_updateDevice(@RequestBody Device device) {
        Date date = new Date();
        device.setUpdateTime(date);
        appUserDao.updateDevice(device);
        Result result=new Result();
        result.setCode("200");
        result.setMsg("succese");
        return result;

    }
    @ApiOperation(value = "根据组id获取设备")
    @GetMapping("/devicelist/get/{id}")
    public List<Device> devices(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getDeviceById(id)));
        return appUserDao.getDeviceById(id);
    }

    @ApiOperation(value = "根据设备id获取当前设备")
    @GetMapping("/devicelist/getone/{id}")
    public Device deviceOne(@PathVariable Long id) {
        log.info(id + "" + JSON.toJSON(appUserDao.getDeviceById(id)));
        return appUserDao.getOneDeviceById(id);
    }


    @LogAnnotation
    @PostMapping("/devicelist/add")
    @ApiOperation(value = "保存/添加设备")
    public int saveDevice(@RequestBody Device device) {
        return appUserDao.saveDevice(device);
    }

    @DeleteMapping("/devicelist/delete/{id}")
    @ApiOperation(value = "删除设备")
    public void deleteDevice(@PathVariable Long id) {
        appUserDao.deleteDevice(id);
    }

    @LogAnnotation
    @PutMapping("/devicelist/update")
    @ApiOperation(value = "更新设备")
    public void updateDevice(@RequestBody Device device) {
        Date date = new Date();
        device.setUpdateTime(date);
        appUserDao.updateDevice(device);
    }

    @GetMapping("/devicelist")
    @ApiOperation(value = "用户列表")
    public PageTableResponse listDevice(PageTableRequest request) {
        Long groupid = Long.parseLong((String) request.getParams().get("groupid"));
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return appUserDao.countDevice(request.getParams(), groupid);
            }
        }, new ListHandler() {
            @Override
            public List<Device> list(PageTableRequest request) {
                List<Device> list = appUserDao.listDevice(groupid, request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除App用户")
    public void delete(@PathVariable Long id) {
        appUserDao.delete(id);
    }
}
